#include "NetWorkServer.h"
#include "HttpCmdProcess.h"
#include "Protocol/ProtocolApi.h"

using namespace Protocol;

NetWorkServer *NetWorkServer::sm_netWorkServer = nullptr;
mutex NetWorkServer::sm_netWorkServerLock;

NetWorkServer *NetWorkServer::instance(){
	if(sm_netWorkServer == nullptr){
        lock_guard<mutex> instanceLock(sm_netWorkServerLock);
		sm_netWorkServer = new NetWorkServer();
	}
	return sm_netWorkServer;
}


NetWorkServer::NetWorkServer(){
	RegistRPC();
}

void NetWorkServer::RegistRPC(){
	RPCMethodMap method_map;

	method_map.emplace("GetNetwork", CRPCFuntion::CreateRpc([this](const Json::Value &request, const BufferMap::Ptr &inMap, Json::Value &response, BufferMap::Ptr &outMap){
		return GetNetwork(request, inMap, response, outMap);
	}));

	method_map.emplace("SetNetwork", CRPCFuntion::CreateRpc([this](const Json::Value &request, const BufferMap::Ptr &inMap, Json::Value &response, BufferMap::Ptr &outMap){
		return SetNetwork(request, inMap, response, outMap);
	}));

	method_map.emplace("GetNetworkStatus", CRPCFuntion::CreateRpc([this](const Json::Value &request, const BufferMap::Ptr &inMap, Json::Value &response, BufferMap::Ptr &outMap){
		return GetNetworkStatus(request, inMap, response, outMap);
	}));

	IProtocolInterface::GetInstance()->RegistProtocol("NetWork", method_map);
}

bool NetWorkServer::SetNetwork(const Json::Value &request, const Fdt::BufferMap::Ptr &inMap, Json::Value &response, Fdt::BufferMap::Ptr &outMap){
	if(!request.isMember("Param")){
		return false;
	}
	return Media::HttpCmdProcess::instance()->SetNetwork(request["Param"]);
}


bool NetWorkServer::GetNetwork(const Json::Value &request, const Fdt::BufferMap::Ptr &inMap, Json::Value &response, Fdt::BufferMap::Ptr &outMap){
	Json::Value table;
	if(!Media::HttpCmdProcess::instance()->GetNetwork(table)){
		response["msg"] = "get Wired Network faild!";
		return false;
	}
	response["data"]["Param"] = table;
	return true;
}


bool NetWorkServer::GetNetworkStatus(const Json::Value &request, const Fdt::BufferMap::Ptr &inMap, Json::Value &response, Fdt::BufferMap::Ptr &outMap){
	int status = mii_diag("eth0");
	bool ret = false;
	if(status == 0){
		ret = true;
	}
	response["data"]["Param"]["IsConnect"] = ret;
	return true;
}



